/**
 * Notes: 云函数业务主逻辑
 * Ver : CCMiniCloud Framework 2.8.1 ALL RIGHTS RESERVED BY cclinUX0730 (wechat)
 * Date: 2020-09-05 04:00:00 
 */
const util = require('../helpers/util.js');
const cloudBase = require('../cloud/cloud_base.js');
const cloudUtil = require('../cloud/cloud_util.js');
const timeUtil = require('../helpers/time_util.js');
const dataUtil = require('../helpers/data_util.js');
const appUtil = require('./app_util.js');
const appCode = require('./app_code.js');
const appOther = require('./app_other.js');
const config = require('../../config/config.js');
const taskMgr = require('../platform/task/task_mgr.js');
const router = require('../router/router');
const { safeGet, formatResponse } = require('../utils/util');
global.PID = 'unknown';

// 初始化任务管理器
let taskInitialized = false;

async function app(event, context, wxContext = {}) {
	try {
		console.log('[Application] 开始处理请求');
		
		// 提取关键参数
		const route = safeGet(event, 'route', '');
		const params = safeGet(event, 'params', {});
		
		// 记录请求信息
		console.log('[Application] 请求路由:', route);
		console.log('[Application] 请求参数:', params);
		
		// 检查企业微信环境
		const isQyWxEnv = params.isQyWx === true || params.env === 'qywx' || wxContext.FROM_WXWORK === true;
		if (isQyWxEnv) {
			console.log('[Application] 检测到企业微信环境');
			
			// 添加企业微信环境标记
			params._isQyWx = true;
			
			// 添加企业微信上下文信息
			if (wxContext) {
				params._qywxContext = {
					CORPID: wxContext.CORPID,
					OPENID: wxContext.OPENID
				};
			}
		}
		
		// 执行路由解析
		const handler = router.resolve(route);
		if (!handler) {
			console.error('[Application] 未找到路由处理器:', route);
			return formatResponse(404, `未找到路由: ${route}`, null);
		}
		
		// 执行处理函数
		console.log('[Application] 调用路由处理器:', handler.name);
		const result = await handler(params, wxContext);
		
		// 调用成功，返回结果
		return formatResponse(200, 'success', result);
	} catch (error) {
		// 记录错误
		console.error('[Application] 执行错误:', error);
		
		// 如果是已知错误，使用其状态码和消息
		if (error.code && error.message) {
			return formatResponse(error.code, error.message, null);
		}
		
		// 未知错误，返回500
		return formatResponse(500, error.message || '服务器内部错误', null);
	}
}

// 事前处理
function beforeApp(method) {
	switch (method) {
		case 'demo': {
			return appUtil.handlerAppErr('本系统仅为用户体验演示，后台提交的操作均不生效！如有需要请联系作者微信cclinux0730', appCode.LOGIC);
		}
	}
	console.error('事前处理, Method Not Find = ' + method);
}

// 展示当前输入数据
function showEvent(event) {
	console.log(event);
}

module.exports = app;